<template>
	<view class="">
		<cu-custom bgColor="" :isBack="true" :isTitle="false">
			<block slot="backText" class="titilestyle">{{title}}</block>
		</cu-custom>

		<scroll-view scroll-y="true" :style="{height: swiperHeight+'px'}" class="">
			<view class="bg-white movable-boxes middle" :style="{width:paper.w*1.06+'px',height:paper.h*1.06+'px'}">
				<movable-area class=" bar-card r-box" :style="{width:paper.w-24+'px',height:paper.h-24+'px'}">
					<movable-view v-for="(item,index) in imgData" direction="all" class="r-boxes" :x="item.x"
						:key="index" :y="item.y" @change="change($event,index)"
						:style="{width:item.w+'px',height:item.h+'px'}" :disabled="item.ismove">

						<view class="middle cancel" v-if="index==imgIndex" @click="close(index)">
							<text class="cuIcon-close text-white"></text>
						</view>

						<view class="middle rotate" @click="rotate(index)" v-if="index==imgIndex">
							<text class="cuIcon-refresh text-white"></text>
						</view>

						<view class="middle scale" @touchstart="start($event,index)" @touchmove="move($event,index)"
							v-if="index==imgIndex" @touchend="cancel($event,index)">
							<text class="iconfont icon-fangda text-white"></text>
						</view>

						<view class="r-boxes-item " :animation="item.animation" :class="index==imgIndex?'r-box-item':''"
							@click="openTouch(index)"
							:style="{width:item.w+'px',height:item.h+'px',backgroundImage:'url('+item.src+')'}">
						</view>

					</movable-view>
				</movable-area>
			</view>

			<view class="basis-xll middle padding-sm" @click="getImg('card')">
				<text class="cuIcon-camerafill "></text><text class="text-blue">添加图片</text>
			</view>
			<!-- <view class="basis-xll middle padding-sm" @click="save">
				<text class=""></text><text class="text-blue">保存</text>
			</view> -->

			<!--   预览图片 -->
			<!-- <view class="basis-xll middle bg-white" >
				<image :src="postData.src" class="viewImage" mode="heightFix" @click="preview(postData.src)"
					:style="{width:paper.w+'px',height:paper.h+'px'}" v-if="postData.src"></image>
			</view> -->
			<!--   预览图片 -->


		</scroll-view>


		<button class="sumbit bg-blue" type="" @click="sumbit" v-if="!preImage">确定</button>
		<button class="sumbit bg-blue" type="" @click="sumbit" v-if="preImage">取消</button>


		<!-- 生成图片区域 -->
		<view class="paper-box bg-white middle " v-if="preImage"
			:style="{width:paper.w*1.08*paper.pixelRatio+'px',height:paper.h*1.08*paper.pixelRatio+'px'}">
			<canvas class="firstCanvas bg-white"
				:style="{width:paper.w*paper.pixelRatio+'px',height:paper.h*paper.pixelRatio+'px'}"
				canvas-id="firstCanvas" id="firstCanvas">

			</canvas>
		</view>
		<!-- 生成图片区域 -->

		<!--上传图片 -->



		<ShowUpload :progress="progress" @closeUpload="closeUpload" v-if="progress!=0"></ShowUpload>


	</view>
</template>

<script>
	import ShowUpload from "../../components/upload.vue"
	let uploadTask = null;
	export default {
		components: {
			ShowUpload
		},
		data() {
			return {
				title: "证件打印",
				src: '',
				swiperHeight: 0,
				index: -1,
				ctx: null,
				cardList: ['身份证打印'],
				postData: {
					src: ""
				},
				specs: [{
						name: "A4",
						w: 210,
						h: 297
					},

					{
						name: "A3",
						w: 297,
						h: 420
					},

					{
						name: "A5",
						w: 148,
						h: 210
					}
				],
				speceIndex: 0,
				specsL: [],

				paper: {
					w: 0,
					h: 0,
					pixelRatio: 1, //分辨率
					min: 0.2,
					max: 0.9,
				},
				imgIndex: 0,
				imgData: [], //图片对象
				animation: null,
				preImage: false,
				info: {

				},
				progress: 0,
				serverUrl: this.apiHost + '/comm/imageUp',


			}
		},
		onLoad(option) {
			this.info = JSON.parse(option.data);
			this.title = this.info.name;
			this.info.shop_id = option.shop_id;
		},
		onReady() {
			this.specs.forEach((e) => {
				this.specsL.push(e.name)
			});
			this.animation = uni.createAnimation({ //旋转产生动画效果 
				duration: 1000,
				timingFunction: 'ease'
			});
			this.ctx = uni.createCanvasContext("firstCanvas");

			this.drawRegion(); //绘制区域
		},
		onShow() {
			this.preImage = false;
		},
		methods: {
			/**
			 * 绘制区域 
			 */
			drawRegion() {
				this.getInfo().then((e) => {
					let b = this.specs[this.speceIndex]; //获取纸张大小比例
					this.paper.pixelRatio = e.pixelRatio; //手机分辨率
					this.paper.w = e.screenWidth * 0.86; //绘制区域宽 92%
					this.paper.h = ((b.h * this.paper.w) / b.w).toFixed(1); //绘制区域高
					this.swiperHeight = e.screenHeight - (e.custom.top + e.custom.height) - 60; //滚动区域
				})
			},

			/**
			 * 选择规格
			 * @param {Object} e
			 */
			selectSpec(e) {
				this.speceIndex = e.detail.value;
				this.drawRegion();
			},

			/**
			 * @param {Object} e
			 */
			addImg(e) {
				let imgData = {
					w: e.width,
					h: e.height,
					x: 0,
					y: 0,
					clx: 0,
					cly: 0,
					rotate: 0,
					ismove: false,
					animation: {},
					animationData: null,
					src: e.url,
				}
				let scale = () => {
						imgData.w = (this.paper.w - 48) * 0.6;
						imgData.h = (imgData.w * e.height) / e.width;
					}
					(imgData.w > this.paper.w * this.paper.max) ? scale() : "";

				if (this.imgData.length > 0) {
					let arr = this.imgData.sort((a, b) => {
						return b.y - a.y;
					})
					imgData.y = arr[0].y + arr[0].h + 30;
				}

				imgData.x = (this.paper.w - imgData.w - 30) / 2;
				this.imgData.push(imgData);
				this.imgIndex = this.imgData.length - 1;

			},

			/**
			 * 选中
			 * @param {Object} index
			 */
			openTouch(index) {
				this.imgIndex = index;
			},
			/**
			 * 旋转 创建旋转动画
			 * @param {Object} index
			 */
			rotate(index) {
				this.imgData[index].animation = this.animation;
				this.imgIndex = -1;
				this.imgData[index].rotate += 90;
				this.animation.rotate(this.imgData[index].rotate).step();

				setTimeout(() => {
					this.imgData[index].animation = this.animation.export();
					this.imgIndex = index;
					this.imgData[index].animation = {};
				}, 1000);
			},
			start(e, index) {
				this.imgData[index].ismove = true;
				this.imgData[index].clx = e.touches[0].clientX;
				this.imgData[index].clx = e.touches[0].clientY;
			},
			move(e, index) {
				//this.imgData[index].ismove = false;
				let dirction = 1;
				let w = e.touches[0].clientX - this.imgData[index].clx;
				let h = e.touches[0].clientY - this.imgData[index].clx;
				if (w < 0 || h < 0) {
					dirction = -1;
				}

				let l = Math.sqrt(w * w + h * h) * 0.05;
				let ww = (this.imgData[index].w + l * dirction);
				let hh = (this.imgData[index].h + l * dirction);

				(ww < (this.paper.w - 48) * this.paper.max && ww > this.paper.w * this.paper.min) ? (() => {
					this.imgData[index].w += l * dirction;
					this.imgData[index].h += l * dirction;
				})() : "";

				this.imgData[index].clx = e.touches[0].clientX;
				this.imgData[index].cly = e.touches[0].clientY;
			},
			cancel(e, index) {
				this.imgData[index].ismove = false;
			},
			close(index) {
				this.imgData.splice(index, 1);
				this.$forceUpdate();
			},
			change(e, index) {
				this.imgData[index].x = e.detail.x;
				this.imgData[index].y = e.detail.y;
			},
			scale(e) {
				console.log(e);
			},
			PickerChange(e) {
				this.index = e.detail.value
			},
			update(e) {
				console.log(e);
				this.addImg(e);
			},
			getImg(type) {
				uni.chooseImage({
					count: 1, //默认
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {

						this.src = res.tempFilePaths;
						uni.navigateTo({
							url: "./sliceImg?src=" + this.src + "&type=" + type
						})
					}
				});
			},
			/**
			 * 生成图片
			 */
			craeteImg() {
				let dramImg = (res) => {
					this.ctx.save();
					let x = res.x + 12 + (res.w / 2),
						y = res.y + 12 + (res.h / 2);
					this.ctx.translate(x * this.paper.pixelRatio, y * this.paper.pixelRatio);
					this.ctx.rotate(res.rotate * (Math.PI / 180));
					this.ctx.drawImage(res.src, -res.w / 2 * this.paper.pixelRatio, -res.h / 2 * this.paper.pixelRatio,
						res.w * this.paper.pixelRatio, res.h * this.paper.pixelRatio);
					this.ctx.translate(-x * this.paper.pixelRatio, -y * this.paper.pixelRatio);
					//处理叠加旋转
					this.ctx.restore();
				}
				let i = 0;
				this.imgData.forEach((res) => {
					i++;
					dramImg(res);
					if (i == this.imgData.length) {
						this.ctx.draw();
						console.log("rander success");
						setTimeout(() => {
							this.save();
						}, 500)
					}

				})

			},
			//确认图片
			sumbit() {
				if (this.imgData.length == 0) {
					uni.showToast({
						title: "请选择证件",
						icon: "none"
					})
					return
				}
				this.preImage = (this.preImage) ? false : true;
				if (this.preImage) {
					uni.showLoading({
						title: "生成中...",
					})
					setTimeout(() => {
						uni.hideLoading();
						this.ctx = uni.createCanvasContext("firstCanvas");
						this.ctx.clearRect(0, 0, this.paper.w, this.paper.h);
						this.craeteImg();
					}, 500)
				}
			},
			/**
			 * 保存图片
			 */
			save() {
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: this.paper.w * this.paper.pixelRatio,
					height: this.paper.h * this.paper.pixelRatio,
					destWidth: this.paper.w * this.paper.pixelRatio,
					destHeight: this.paper.h * this.paper.pixelRatio,
					canvasId: 'firstCanvas',
					fileType: 'png',
					quality: 1,
					success: (res) => {
						this.postData.src = res.tempFilePath;

						this.upload(res.tempFilePath).then(r => {
							this.info.url = r;

							uni.navigateTo({
								url: "../order/orderSub?postInfo=" + JSON.stringify(this.info)
							})
						}, e => {

							this.closeUpload("cancel");

						})
					}
				})
			},
			//查看图片
			preview(item) {
				uni.previewImage({
					urls: [item]
				})

			},
			showToast(content) {
				uni.hideLoading();
				uni.showToast({
					title: content,
					icon: "none"
				});

			},
			//取消上传
			closeUpload(type) {
				switch (type) {
					case "cancel":
						uploadTask.abort();
						this.progress = 0;
						uploadTask = null;
						break;
				}
			},
			//上传图片
			upload(path) {
				return new Promise((resolve, reject) => {
					uploadTask = uni.uploadFile({
						url: this.serverUrl,
						fileType: 'image',
						name: 'upload-images',
						filePath: path,
						success: (uploadFile) => {
							if (uploadFile.statusCode == 200) {
								resolve(uploadFile.data);
								this.closeUpload("cancel");
							} else {
								this.closeUpload("cancel");
								this.showToast("上传出错，请稍后再试");
								reject();
							}
						},
						fail: (e) => {
							this.showToast("上传出错，请稍后再试");
							this.closeUpload("cancel");
							reject();
						}
					});
					uploadTask.onProgressUpdate((res) => {
						this.progress = res.progress;
					})
				})


			}


		}



	}
</script>

<style scoped>
	@import "@/app/CloudPrint/static/iconfont.css";

	.item-box-spec {
		margin: auto;
	}

	.bg-white {
		background-color: white;
	}

	.rotate {
		width: 50rpx;
		height: 50rpx;
		background-color: #1270E0;
		border-radius: 50%;
		bottom: 0rpx;
		left: 0rpx;
		z-index: 9;
		position: absolute;
	}

	.cancel {
		width: 50rpx;
		height: 50rpx;
		background-color: #1270E0;
		border-radius: 50%;
		top: 0;
		left: 0;
		z-index: 9;
		position: absolute;
	}

	.scale {
		width: 50rpx;
		height: 50rpx;
		background-color: #1270E0;
		border-radius: 50%;
		bottom: 0;
		right: 0;
		z-index: 9;
		position: absolute;
	}

	.r-box {
		margin: auto;

		overflow: hidden;
	}

	.r-box-item {
		border: 3px solid #1270E0;
		position: relative;


	}

	.r-boxes-item {

		background-size: 100% 100%;
		background-repeat: no-repeat;
	}



	.inro-card {
		width: 92%;
		margin: 20upx auto;
		background: #FFFFFF;
		box-shadow: 0px 0px 10upx 0px rgba(0, 0, 0, 0.05);
		border-radius: 20upx;
		padding: 30upx;
		position: relative;
	}

	.movable-boxes {
		background: #FFFFFF;
		margin: auto;
		border: 2rpx solid #000000;
		box-shadow: 0px 0px 10rpx 0px rgba(0, 0, 0, 0.05);
	}

	.viewImage {
		margin: auto;
	}

	.paper-box {
		position: absolute;
		overflow: hidden;
		z-index: -1;
		opacity: 0;
		top: 0;
		left: 24rpx;
	}

	.firstCanvas {
		z-index: -555;
		opacity: 0;
		position: fixed;
		left: 100vw;
	}



	.bar-card {
		margin: auto;
		box-shadow: 0px 0px 9px 0px rgba(82, 255, 226, 0.23) inset;
		background: linear-gradient(to left, #999999, #999999) left top no-repeat, linear-gradient(to bottom, #999999, #999999) left top no-repeat, linear-gradient(to left, #999999, #999999) right top no-repeat, linear-gradient(to bottom, #999999, #999999) right top no-repeat, linear-gradient(to left, #999999, #999999) left bottom no-repeat, linear-gradient(to bottom, #999999, #999999) left bottom no-repeat, linear-gradient(to left, #999999, #999999) right bottom no-repeat, linear-gradient(to left, #999999, #999999) right bottom no-repeat;
		background-size: 4rpx 60rpx, 60rpx 4rpx, 4rpx 60rpx, 60rpx 4rpx;

	}

	.sumbit {
		width: 92%;
		margin: auto;
	}

	.content-card-mask {
		overflow: hidden;
	}

	.cuIcon-camerafill {
		color: #3E8EF7;
		font-size: 48rpx;
		margin-right: 14rpx;
	}
</style>
<style lang="scss">
	.content-card {
		margin: 20upx auto;
		width: 0.92*750rpx;
		height: (0.92/1.56)*750rpx;
		background: #FFFFFF;
		position: relative;
	}

	.content-card-mask {
		width: 0.92*750-8rpx;
		height: (0.92/1.56)*750-8rpx;
		margin-top: 4rpx;
		margin-left: 4rpx;
		position: absolute;
	}
</style>
